package com.kate.mall.member.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kate.mall.common.utils.PageUtils;
import com.kate.mall.member.dao.MemberFormidDao;
import com.kate.mall.member.entity.MemberFormidEntity;
import com.kate.mall.member.service.MemberFormidService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kate.mall.common.utils.Query;

@Service("memberFormidService")
public class MemberFormidServiceImpl extends ServiceImpl<MemberFormidDao, MemberFormidEntity> implements MemberFormidService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberFormidEntity> page = this.page(
                new Query<MemberFormidEntity>().getPage(params),
                new QueryWrapper<MemberFormidEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public Integer updateUserFormId(MemberFormidEntity memberFormidEntity) {
        //更新或者删除缓存
        if (memberFormidEntity.getIsprepay().equals(1) && memberFormidEntity.getUseamount() > 1) {
            memberFormidEntity.setUseamount(memberFormidEntity.getUseamount() - 1);
            memberFormidEntity.setUpdateTime(LocalDateTime.now());
            return baseMapper.updateById(memberFormidEntity);
        } else {
            return baseMapper.deleteById(memberFormidEntity.getId());
        }
    }

    @Override
    public MemberFormidEntity queryUserFormIdByOpenId(String touser) {
        //符合找到该用户记录，且可用次数大于1，且还未过期
        return baseMapper.selectOne(Wrappers.<MemberFormidEntity>lambdaQuery()
                .eq(MemberFormidEntity::getOpenid,touser)
                .gt(MemberFormidEntity::getExpireTime,LocalDateTime.now()));
    }

}